/**
 * Created by zaranengap on 2017/7/3.
 * refactoring by zhouli on 2019/2/26.
 */
import React from 'react';
import {connect} from 'react-redux';
import {message, Tabs, Spin, Modal, Button} from 'antd';
import httpFetch from 'share/httpFetch';
import menuRoute from 'routes/menuRoute';
import Parallax from 'parallax-js';
import baseService from 'share/base.service';
import errorMessage from 'share/errorMessage';
import {
  redirect_by_url_for_mail_approve, sso_huilianyi,
  redirect_by_url_for_approval_route
} from 'components/method/sso';
import 'styles/login/login.scss';
import {getUrlSearchParams, messages, getToken, isShowSSOLogining, getTime} from 'share/common';
import config from 'config';
import configureStore from 'stores';
import slogan from 'containers/login/functional-components/slogan';

import BG from 'images/login/BG.jpg';
import logo from 'images/login/logo.png';
import logoEn from 'images/login/logo-en.png';
import layer1 from 'images/login/layer01.png';
import layer2 from 'images/login/layer02.png';
import layer3 from 'images/login/layer03.png';
import companyLogin from 'images/login/company-login.png';
import wechatLogin from 'images/login/wechat-login.png';
import accountLogin from 'images/login/account-login.png';
import tryLogin from 'images/login/try-login.png';
import {setTenantMode, setAdminMode, setAuthToken} from "actions/main";
import StopAnnonuce from 'components/template/stop-annonuce/stop-annonuce';
import LoginService from 'containers/login/login.service';
import AccountLogin from 'containers/login/components/account-login/account-login';
import CompanyLogin from 'containers/login/components/company-login/company-login';
import QcodeLogin from 'containers/login/components/qcode-login/qcode-login';
import TryLogin from 'containers/login/components/try-login/try-login';
import 'styles/login/login-refactoring-ui.scss'
import * as dingtalk from 'dingtalk-jsapi';
import mainService from 'containers/main.service';

const TabPane = Tabs.TabPane;
//二维码登录排除

const loginWayAllObj = {
  "ACCOUNT": function (self) {
    return {
      key: "ACCOUNT",
      message: messages('login.key27')/*账号登录*/,
      active: false,
      icon: accountLogin,
      component: <AccountLogin
        onRef={self.onMountAccountLogin}
        login={self.loginAction}/>,
    }
  },
  "TRIAL": function (self) {
    return {
      key: "TRIAL",
      message: messages('login.key44')/*免费体验*/,
      active: false,
      icon: tryLogin,
      component: <TryLogin
        onRef={self.onMountTryLogin}
        login={self.loginAction}/>,
    }
  },
  "ENTERPRISE": function (self) {
    return {
      key: "ENTERPRISE",
      message: messages('login.key45')/*企业登录*/,
      active: false,
      icon: companyLogin,
      component: <CompanyLogin
        onRef={self.onMountCompanyLogin}
        login={self.loginAction}/>,
    }
  },
  "WECHAT": function (self) {
    return {
      key: "WECHAT",
      message: messages('login.key46')/*微信登录*/,
      jumpUrlAction: self.wxLoginJumpAction,
      active: false,
      icon: wechatLogin,
    }
  },
};

const pageRouteMap= {
  'expenseList': 'expense-report', // 报销单列表
  'requestList': 'request', // 申请单列表
  'loanBillingList': 'my-borrow', // 借款单列表
  'myAccountList': 'my-account', // 账本列表
  'approvalList': 'approve' // 审批
}
class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userProtocolVisible: false,
      isSSOLogining: false,// 单点登录是否正在授权登录
      defaultTabKey: 'qcode',//默认打开的tab
      username: '',
      password: '',
      loginType: '',
      clientName: '',
      tenantId: "",
      loginId: undefined,//是一种单点登录重定向url上带有的参数
      loading: false,
      hasCodeLogin: false,//是否有二维码登录
      codeLoginMessage: messages('login.key48')/*二维码登录*/,//二维码登录的title
      loginWayList: [
        //就算是接口失败，也设置这种方式
        {
          key: "Account",
          message: messages('login.key27')/*账号登录*/,
          active: true,
          icon: accountLogin,
          component: <AccountLogin
            onRef={this.onMountAccountLogin}
            login={this.loginAction}/>,
        },
      ],
      wayLoading: false,
      pathLoginWay: "",
      pageRoute: "", // 标识要跳去的页面
    }
  }

  componentWillMount() {
    //this.pathLoginWay();
  }

  componentDidMount() {
    this.setState({
      isSSOLogining: isShowSSOLogining()
    })
    this.loginWayAnalysis();
    this.initScene();
    this.hlyError();
    //this.getLoginWayConfig(this);
    this.props.onRef && this.props.onRef(this);
  }


  // 获取运营平台配置的登录方式
  getLoginWayConfig = (self) => {
    const {pathLoginWay} = this.state;
    this.setState({
      wayLoading: true,
    });
    LoginService.getLoginWayConfig(this.props.language.code, loginWayAllObj, self, pathLoginWay)
      .then(res => {
        if (res.loginWayList.filter(item => item.key === pathLoginWay).length) {
          this.setState({
            defaultTabKey: pathLoginWay,
          });
        }
        this.setState({
          wayLoading: false,
          hasCodeLogin: res.hasCodeLogin,
          loginWayList: res.loginWayList,
          codeLoginMessage: res.codeLoginMessage,
        })
      })
      .catch(err => {
        this.setState({
          wayLoading: false,
        });
      })
  };

  //钉钉单点登录
  handleDingDing = (request) => {
    let href = window.location.href;
    let corpId = href.match(/corpId=(.*)/)[1];

    let _this = this;
    let params = {
      scope: 'write',
      grant_type: 'password',
      password: '',
      username: "",
      companyOID: "",
      corpId: corpId,
      dingTalkLogin: 'Y'
    };
    let basicHeader = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Cache-Control': 'no-cache',
      "Authorization": "Basic QXJ0ZW1pc0RpbmdUYWxrOm5MQ253ZEloaXpXYnlrSHl1Wk02VHBRRGQ3S3dLOUlYREs4TEdzYTdTT1c=",
    };
    let directUrl = request.params;
    directUrl= directUrl && atob(directUrl)
    try {
      dingtalk.ready(() => {
        dingtalk.runtime.permission.requestAuthCode({
          corpId: corpId, // 企业id
          onSuccess: function (info) {
            params.username = info.code;
            let items = {
              ddsso: "ddsso",
              params,
              headers: basicHeader,
              useAuthService: true,
            };
            _this.login(items);
            _this.setState({
              isSSOLogining: true,
            })
          },
          onFail: function (err) {
            console.log("钉钉onFail", JSON.stringify(err))
            //reject(err);
          }
        });
      });
    } catch (e) {
      console.log("catch", e)
    }
  };

  // 登录方式分析
  loginWayAnalysis = () => {

    //let request = new UrlSearch();
    let request = new getUrlSearchParams();
    let loginWay = this.getWhichWay(request);
    sessionStorage.setItem('hly.loginType', request.loginType);
    // 先存储pageRoute 方便后面支持其它登录方式
    const pageRoute= request['pageRoute']
    pageRoute && (this.setState({
      pageRoute
    }))

    switch (loginWay) {
      case "corpId": {//钉钉单点登录
        this.handleDingDing(request);
        break;
      }
      case "mailApprove": {
        this.mailApprove();
        break;
      }
      case "loginId": {
        this.setState({
          isSSOLogining: true,
          username: request.code,
          password: request.code,
          loginType: "sso",
          loginId: request.loginId,
        }, () => {
          this.login()
        });
        break;
      }
      case "auth_code": {
        this.setState({
          isSSOLogining: true,
          username: request.auth_code,
          password: request.auth_code,
          loginType: request.state ? request.state : "wxweb",
          clientName: "",
        }, () => {
          this.login()
        });
        break;
      }
      case "approval_route": {
        this.setState({
          isSSOLogining: true,
          username: request.authorizationCode,
          password: request.authorizationCode,
          loginType: request.loginType,
          clientName: "",
        }, () => {
          this.login()
        });
        break;
      }
      case "user-id": {
        this.setState({ // 私有化单点登录改造 by ting.zhang  loginType=privateSso&user-id=XXX
          isSSOLogining: true,
          username: request['user-id'],
          password: request['user-id'],
          loginType: request.loginType,
          // client_name: "",
        }, () => {
          this.login();
        });
        break;
      }
      case "bossSso": {
        this.setState({ // Boss 单点登录  loginType=bossSso&user-id=XXX
          isSSOLogining: true,
          username: request['ssoToken'],
          password: request['ssoToken'],
          loginType: request.loginType,
          // client_name: "",
        }, () => {
          this.login();
        });
        break;
      }
      case "maintenanceSso": {
        this.setState({ // 运维平台登陆
          isSSOLogining: true,
          username: request['mToken'],
          password: request['mToken'],
          loginType: request.loginType,
          // client_name: "",
        }, () => {
          this.login();
        });
        break;
      }
      //运营系统进来的
      case "operation": {
        this.setState({
          isSSOLogining: true,
          username: request.code,
          password: "",
          loginType: "operation",
          clientName: "",
          tenantId: request.tenantId,
        }, () => {
          this.login()
        });
        break;
      }
      case "SSO": {
        // 另一种企业单点直登录
        this.setState({
          isSSOLogining: true,
          loginType: request.loginType,
          password: request.code,
          username: request.code,
          clientName: ""
        }, () => {
          this.login();
        });
        break;
      }
      case "ssoDirect": {
        if (request.clientName && request.userinfo) {
          //就算是存在 token，也重新登录 task 23148
          this.loginDecide(request);
        } else if (!LoginService.isSelfDomain(window.location.hostname)) {
          //其他二级域名都要重新登录
          this.loginDecide(request);
        } else {
          //单独登录
          if (getToken()) {
            configureStore.store.dispatch(setAuthToken(JSON.parse(getToken())));
            this.setState({loading: true});
            baseService.getInfo()
              .then(() => {
                this.setState({loading: false});
                this.goMainPage();
              })
              .catch(e => {
                //这个console对排查登录出错非常非常有用，不要删除
                console.log("ssoDirect-err", e)
                this.setState({loading: false});
                errorMessage(e, messages('dashboard.key44'/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/))
              })
          } else {
            //询问哪一种登录方式
            this.loginDecide(request);
          }
        }
        break;
      }
    }
  };
  //获取登录方式
  getWhichWay = (request) => {
    //不要修改 loginWayArr 元素的顺序。只可往后添加，不要动以前的。
    //corpId是钉钉单点登录的参数,operation是从运营系统直接跳转至中控的
    let loginWayArr = ['mailApprove', 'loginId', 'auth_code', 'approval_route', 'SSO', 'ssoDirect', 'corpId', "operation" ];
    if (request.mailApprove) {
      return loginWayArr[0]; // mailApprove
    } else if (request.loginId) {
      return loginWayArr[1]; // loginId
    } else if (request.auth_code) {
      return loginWayArr[2]; // auth_code
    } else if (request.approval_route && request.loginType === "authorizationCode" && request.authorizationCode) {
      return loginWayArr[3]; // approval_route
    } else if (request.corpId) {
      return loginWayArr[6];
    } else if (request.source === "operation") {
      return loginWayArr[7];
    } else if (request.loginType === "bossSso" && request['ssoToken']) {
      return 'bossSso';
    } else if (request.loginType === "maintenanceSso" && request['mToken']) {
      return 'maintenanceSso';
    }else {
      if (request.loginType && request.code) {
        return loginWayArr[4];
      } else if (request.loginType && request['user-id']) {
        return 'user-id';
      } else {
        return '';
      }
    }
  };
  //hlyError
  hlyError = () => {
    let error = localStorage.getItem('hly.error');
    if (error) {
      try {
        message.error(JSON.parse(error));
        localStorage.removeItem('hly.error');
      } catch (e) {
        message.error(messages('common.error'));
        localStorage.removeItem('hly.error');
      }
    }
  };
  //初始化场景
  initScene = () => {
    let scene = document.getElementById('scene');
    new Parallax(scene, {
      calibrateX: true
    });
  };
  //跳转到首页
  goMainPage = () => {
    const {user, isOldCompany, newPermissionSortedMenus} = this.props;
    const {pageRoute}= this.state
    let url = menuRoute.indexUrl;
    user.mock && configureStore.store.dispatch(setAdminMode(true));
    if (user.enableNewPermission) {
      const checkMenuAuthParams = [!!user.mock, user.hasTenantRole, isOldCompany];
      let firstPath = mainService.lookForFirstMenu(newPermissionSortedMenus, ...checkMenuAuthParams);
      if (firstPath && firstPath.url) {
        url = firstPath.url;
      }
    }
    console.log('=======pageRoute', pageRoute)
    // 根据pageRoute跳转
    if(pageRoute){
      configureStore.store.dispatch(setTenantMode(false));
      url= menuRoute.getRouteItem(pageRouteMap[pageRoute]).url || url
    }
    this.context.router.push(url);
  };

  //微信登录，跳转到微信扫码授权地址 wxLoginJumpAction
  wxLoginJumpAction = () => {
    let env_url = window.location.protocol + "//" + window.location.host;
    window.location.href = "https://open.work.weixin.qq.com" +
      "/wwopen/sso/3rd_qrConnect?appid=ww75432cba19a38d80&redirect_uri=" +
      env_url +
      "&state=wxweb&usertype=member";
  };
  //邮件审批
  mailApprove = () => {
    if (getToken()) {
      //有token的情况
      redirect_by_url_for_mail_approve();
    } else {
      //没有登录需要进行单点登录
      sso_huilianyi((data) => {
        // sso_huilianyi内部有重定向判断，如果有重定向到其他页面，下面的逻辑不会执行
        baseService.getInfo().then(() => {
          this.setState({loading: false});
          this.goMainPage();
        })
      }, (err) => {
        //这个console对排查登录出错非常非常有用，不要删除
        console.log("mailApprove-err", err)
        //单点登录，用code登录失败
        message.error(messages('dashboard.key44'/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/));
      });
    }
  };
  //设置登录方式
  setloginTypeByloginDecide = (loginType, request) => {
    if (loginType.loginType === "sso") {
      //单点直登录
      this.setState({
        loginType: "sso",
        clientName: ""
      });
      if (!request.logout_sso) {
        //单点登录
        sso_huilianyi((data) => {
          baseService.getInfo().then(() => {
            this.setState({
              isSSOLogining: false,
              loading: false
            });
            this.goMainPage();
          })
        }, (err) => {
          //这个console对排查登录出错非常非常有用，不要删除
          console.log("sso", err)
          this.setState({
            isSSOLogining: false,
          });
          //单点登录，用code登录失败
          message.error(messages('dashboard.key44'/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/));
        });
      } else {
        this.setState({
          isSSOLogining: false,
        });
      }
    } else if (loginType.loginType === "ssoDirect") {
      if (loginType.clientName === "talefull") {
        //这又是另一种特殊的登录方式
        //截取url当做用户名，截取indate当做密码
        this.setState({
          isSSOLogining: true,
          username: request.url,
          password: request.indate,
          loginType: "ssoDirect",
          clientName: loginType.clientName
        }, () => {
          this.login()
        })
      } else {
        //单点直登录
        this.setState({
          isSSOLogining: true,
          username: request.userinfo,
          password: request.userinfo,
          loginType: "ssoDirect",
          clientName: loginType.clientName
        }, () => {
          this.login()
        })
      }
    } else {
      if (request.userinfo && request.clientName) {
        this.setState({
          isSSOLogining: true,
          username: request.userinfo,
          password: request.userinfo,
          loginType: "ssoDirect",
          clientName: request.clientName
        }, () => {
          this.login()
        })
      } else {
        if (request.loginTrail) {
          this.onActiveOtherWay("TRIAL");
        }
        //普通登录
        this.setState({
          isSSOLogining: false,
          loginType: "",
          clientName: ""
        })
      }
    }
  };
  //各种方式的登录处理，单点登录，普通登录，单点直登录
  loginDecide = (request) => {
    // url 上只有参数 code 显示 登录中 loading
    this.setState({
      isSSOLogining: true,
    });
    LoginService.loginDecide()
      .then((res) => {
        let _this = this;
        let data = res.data;
        let localNeedProtocol = localStorage.getItem('localNeedProtocol');
        if (data.needProtocol + "" === "true" && localNeedProtocol !== 'false') {
          this.setState({userProtocolVisible: true});
          // 缓存一下数据，点击 同意协议 之后就走下一步
          this.request = request;
          this.loginType = data;
        } else {
          _this.setloginTypeByloginDecide(data, request);
        }
      })
      .catch((err) => {
        this.setState({
          isSSOLogining: false,
          loginType: "",
          clientName: ""
        })
      })
  };
  //检查登录者语言是否和默认语言一致,页面静态变量有缓存
  checkLoginLanguage = (defaultLoginLanguage) => {
    if (this.props.language && this.props.language.code.toLowerCase() !== defaultLoginLanguage) {
      if (config.appEnv === 'dist') {
        location.href = location.origin + config.newHomepage;
      } else {
        window.location.reload();
      }
      return true;
    }
    return false;
  };
  //登录入口
  login = (ddsso) => {
    let {
      username,
      password,
      loginType,
      clientName,
      loginId,
      tenantId,
    } = this.state;
    let login = {
      username,
      password,
      loginType,
      clientName,
      loginId,
      tenantId
    };
    //钉钉单点登录的header，URL，参数都不一样，要做特殊处理
    if (ddsso && ddsso.ddsso) {
      login = ddsso;
    }
    this.loginAction(login);
  };
  //登录
  loginAction = (login) => {

    //钉钉单点登录的，要先拿到token，调取account接口才能判断是否白名单
    if (login && login.ddsso) {
      httpFetch.login(login)
        .then(res => {
          baseService.getUser()
            .then(info => {
              this.checkWhiteList(null, info.login, "ddsso");
            })
            .catch(err => {
              console.log("getUser-err", err)
              throw err;
            })
        })
        .catch(err => {
          this.childAccountLogin && this.childAccountLogin.setLoading && this.childAccountLogin.setLoading(false);
          this.childTryLogin && this.childTryLogin.setLoading && this.childTryLogin.setLoading(false);
          this.setState({
            loading: false,
            isSSOLogining: false,
          });
          LoginService.delLoginErr(err);
        })

    } else {
      this.checkWhiteList(login, login.username, null);
    }
  };
  /*
  * 检查是否在白名单里面
  * 这个在停机公告期间有用，只有白名单的人才能进入
  * */
  checkWhiteList = (login, name, type) => {
    let defaultLoginLanguage = 'zh_cn';
    if (this.props.language && this.props.language.code) {
      defaultLoginLanguage = this.props.language.code.toLowerCase();
    }
    //this.childStopAnnonuce.getIsWhiteList(name, () => {
      this.setState({loading: true});
      this.childAccountLogin && this.childAccountLogin.setLoading && this.childAccountLogin.setLoading(true);
      this.childTryLogin && this.childTryLogin.setLoading && this.childTryLogin.setLoading(true);
      if (type === "ddsso") {
        this.afterLoginSuccess(defaultLoginLanguage);
      } else {
        this.normalLogin(login, defaultLoginLanguage);
      }
    //});
  };
  //除去钉钉登录以外的登录情况
  normalLogin = (login, defaultLoginLanguage) => {
    httpFetch.login(login.username, login.password, login.loginType, login.clientName, login.loginId, login.cryptType, login.tenantId)
      .then((res) => {
        this.afterLoginSuccess(defaultLoginLanguage);
      })
      .catch(err => {
        this.childAccountLogin && this.childAccountLogin.setLoading && this.childAccountLogin.setLoading(false);
        this.childTryLogin && this.childTryLogin.setLoading && this.childTryLogin.setLoading(false);
        this.setState({
          loading: false,
          isSSOLogining: false,
        });
        LoginService.delLoginErr(err);
      })
  };
  //登录成功后的操作
  afterLoginSuccess = (defaultLoginLanguage) => {
    //getInfo里面有掉很多接口，有一个接口错误就卡死在登录页面，没有提示
    //这边添加一些错误提示
    baseService.getInfo()
      .then(() => {
        this.childAccountLogin && this.childAccountLogin.setLoading && this.childAccountLogin.setLoading(false);
        this.childTryLogin && this.childTryLogin.setLoading && this.childTryLogin.setLoading(false);
        this.setState({
          loading: false,
          isSSOLogining: false,
        });
        // ---下面是邮件审批的逻辑start---
        let Request = new getUrlSearchParams(); //实例化
        if (Request.origin_url_for_mail_approve) {
          redirect_by_url_for_mail_approve();
          return;
        }
        // ---上面是邮件审批的逻辑end---
        //  钉钉消息跳转
        else if (Request.msgRedirectUrl){
          let redirectUrl= Request.msgRedirectUrl
          redirectUrl= redirectUrl && atob(redirectUrl)
          window.location.href= redirectUrl
          return
        }
        else if (Request.loginId) {
          let hly_token = JSON.parse(localStorage.getItem('hly.token'));
          //这种单点登录方式，后端会多返回这么一个字段
          let redirect = hly_token.redirect;
          redirect_by_url_for_approval_route(redirect);
          return;
        } else if (Request.approval_route &&
          Request.loginType === "authorizationCode" &&
          Request.authorizationCode) {
          redirect_by_url_for_approval_route();
          return;
        }else if (Request.messageType) { // 处理私有化对接的常用待办类型，参考[私有化公共改造.md] by ting.zhang
          // url示例：
          // http://X.XX.com/?loginType=privateSso&user-id=xxx&messageType=EXPENSE_REPORT_APPROVAL&targetParams={applicationOID:xxx,expenseReportOID:xxx,approverOID:xxx}
          redirect_by_url_for_approval_route();
          return;
        }

        let isRedirect = this.checkLoginLanguage(defaultLoginLanguage);
        if (isRedirect) {
          return;
        }
        this.goMainPage();
      })
      .catch((err) => {
        this.childAccountLogin && this.childAccountLogin.setLoading && this.childAccountLogin.setLoading(false);
        this.childTryLogin && this.childTryLogin.setLoading && this.childTryLogin.setLoading(false);
        this.setState({
          loading: false,
          isSSOLogining: false,
        });
        //如果某个报错接口没有response则会报错，改成这样
        if (err.response) {
          errorMessage(err.response);
        }
      })
  };
  //登录方式的key发生改变
  onKeyChange = (key) => {
    //需要等待组件渲染完毕
    setTimeout(() => {
      if (key === "qcode") {
        this.childQcodeLogin.getQcode();
      } else {
        this.childQcodeLogin.cancelRequestQcode();
        if (key === "Account") {
          this.childAccountLogin.onActiveKey("Account");
        }
        if (key === "ENTERPRISE") {
          this.childCompanyLogin.companyWayLoginStep1();
        }
      }
    }, 200);
  };
  //点击 tab 切换
  changeQcode = (key) => {
    //如果不是二维码，需要取消掉轮询
    this.setState({
      defaultTabKey: key
    }, () => {
      this.onKeyChange(key);
    });
  };
  //挂载子组件到当前容器：停机公告
  onMountStopAnnonuce = (StopAnnonuce) => {
    this.childStopAnnonuce = StopAnnonuce;
  };
  //挂载子组件到当前容器：二维码登录
  onMountQcodeLogin = (qcodeLogin) => {
    this.childQcodeLogin = qcodeLogin;
  };
  //挂载子组件到当前容器：账号登录
  onMountAccountLogin = (accountLogin) => {
    this.childAccountLogin = accountLogin;
  };
  //挂载子组件到当前容器：公司登录
  onMountCompanyLogin = (companyLogin) => {
    this.childCompanyLogin = companyLogin;
  };
  onMountTryLogin = (tryLogin) => {
    this.childTryLogin = tryLogin;
  };
  //激活当前登录方式
  onActiveOtherWay = (key) => {
    const {loginWayList} = this.state;
    let activeItem = null;
    loginWayList.map((item) => {
      item.active = (key === item.key);
      if (key === item.key) {
        activeItem = item;
      }
    });
    if (activeItem.jumpUrlAction) {
      activeItem.jumpUrlAction();
    } else {
      this.setState({
        defaultTabKey: key,
        loginWayList
      })
    }
    this.onKeyChange(key);
  };
  //渲染登录方式
  renderActiveKey = (loginWayList, hasCodeLogin) => {
    let key = '', message = '', component = '';
    loginWayList.map((item) => {
      if (item.active) {
        key = item.key;
        message = item.message;
        component = item.component;
      }
    });
    if (hasCodeLogin) {
      return (<TabPane tab={message} key={key}>{component}</TabPane>)
    } else {
      return (<div key={key}>{component}</div>);
    }
  };
  //渲染底部的几种登录方式
  renderOtherWay = (loginWayList) => {
    let arr = [];
    loginWayList.map(item => {
      if (!item.active) {
        arr.push(item);
      }
    });
    return arr.map(((item, index) => {
      return (
        <div className="login-item"
             key={item.key}
             onClick={() => {
               this.onActiveOtherWay(item.key)
             }}>
          <div className="img-wrap">
            <img src={item.icon}/>
          </div>
          <div className="text">{item.message}</div>
        </div>
      )
    }))
  };
  //渲染登录方式
  renderWxwebLoading = () => {
    const {hasCodeLogin, wayLoading, isSSOLogining, loginType} = this.state;
    let domain = window.location.protocol + "//" + window.location.hostname;
    if (isSSOLogining || loginType === 'privateSso') {
      return (
        <div className="login-refactoring">
          <div className="login-title-wrap"> {messages('helios.title')/*一站式商旅平台*/}</div>
          <div style={{height: 209, lineHeight: "209px"}}>
            <Spin spinning={isSSOLogining}/>
          </div>
          {/*<div className="login-refactoring-links">
            <a className="login-refactoring-link-left" href="https://www.huilianyi.com/"
               target="_blank">{messages('login.key58')/*访问官网*!/</a>
            <a className="login-refactoring-link-right" href="https://www.huilianyi.com/trial2?type=try" target="_blank">{messages('login.key59')}</a>
          </div>*/}

        </div>
      );
    } else {
      return (
        <div className="login-refactoring">
          <div className="login-title-wrap"> {messages('helios.title')/*一站式商旅平台*/}</div>
          {wayLoading ? <Spin spinning={wayLoading}/> :
            <div>
              <div className="login-tab-wrap">
                {
                  hasCodeLogin ? this.renderHasCodeLogin() : this.renderNoCodeLogin()
                }
              </div>
              {this.renderOtherLoginWay()}
            </div>}
          {/*<div className="login-refactoring-links">
            <a className="login-refactoring-link-left" href="https://www.huilianyi.com/"
               target="_blank">{messages('login.key58')/!*访问官网*!/}</a>
            以后迭代再放开
            <a className="login-refactoring-link-right" href="https://www.huilianyi.com/trial2?type=try" target="_blank">{messages('login.key59')}</a>
          </div>*/}

        </div>

      )
    }
  };
  //有二维码登陆
  renderHasCodeLogin = () => {
    const {loginWayList, defaultTabKey, codeLoginMessage} = this.state;
    return (
      <Tabs activeKey={defaultTabKey}
            size="large"
            onTabClick={this.changeQcode}>
        <TabPane tab={codeLoginMessage}
                 key="qcode"
                 className="qcode-class">
          <QcodeLogin
            login={this.loginAction}
            onRef={this.onMountQcodeLogin}/>
        </TabPane>
        {this.renderActiveKey(loginWayList, true)}
      </Tabs>
    )
  };
  // 没有二维码登录
  renderNoCodeLogin = () => {
    const {loginWayList} = this.state;
    return this.renderActiveKey(loginWayList)
  };

  //渲染其他登录方式
  renderOtherLoginWay = () => {
    const {loginWayList} = this.state;
    if (loginWayList.length > 1) {
      return (
        <div>
          <div className="title-line-wrap">
            <div className="title-line-left"/>
            <div className="title-text">{messages('login.key49')/*其他登录方式*/}</div>
            <div className="title-line-right"/>
            <div className="clear"/>
          </div>
          <div className="login-item-wrap">
            {this.renderOtherWay(loginWayList)}
            <div className="clear"/>
          </div>
        </div>
      )
    }
  };
  confirmProtocol = () => {
    localStorage.setItem('localNeedProtocol', 'false');
    this.setState({userProtocolVisible: false})
    this.setloginTypeByloginDecide(this.loginType, this.request);
  }
  cancelProtocol = () => {
    localStorage.setItem('localNeedProtocol', 'true');
    this.setState({
      userProtocolVisible: false,
    })
  }

  pathLoginWay = () => {
    let path = window.location.href;
    let patt = /(webLogin)=([A-Za-z]*)(\/?)/;
    let arr = path.match(patt);
    if (arr && arr.length && arr[2]) {
      this.setState({
        pathLoginWay: arr[2],
      })
    }
  };

  render() {
    //协议语言取浏览器
    let lang = navigator.language;
    let href = 'https://console.huilianyi.com/register/pages/privacy_statement_en.html';
    if (lang === 'zh-CN') {
      href = 'https://console.huilianyi.com/register/pages/protocol.html';
    }
    if (lang === 'ja') {
      href = 'https://console.huilianyi.com/register/pages/privacy_statement_ja.html';
    }
    const {loginType, userProtocolVisible} = this.state;
    const {language} = this.props;
    const userFooter = (
      <div>
        <Button onClick={this.cancelProtocol}>{messages("common.cancel")}</Button>
        <Button type={'primary'} onClick={this.confirmProtocol}>{messages('login.key10'/*我已阅读并同意*/)}</Button>
      </div>
    );
    return (
      <div className='login login-refactoring-ui'>
        <div className="login-inner">
          <img src={BG} className="background-img"/>
          {this.renderWxwebLoading()}
          <div id="scene">
            {/*<img src={language.locale === 'en' ? logoEn : logo} className="img-logo"/>*/}
            <div data-depth="0.2"><img src={layer1}/></div>
            <div data-depth="0.4"><img src={layer2}/></div>
            <div data-depth="0.6"><img src={layer3}/></div>
          </div>
          {/*{slogan(loginType, language.locale)}*/}
          {/*<StopAnnonuce onRef={this.onMountStopAnnonuce}/>*/}
        </div>

        {/*单点登录前需要同意*/}
        <Modal
          width={650}
          bodyStyle={{maxHeight: 400, overflow: 'hidden', paddingTop: 0}}
          maskClosable={false}
          keyboard={false}
          zIndex={3000}
          title={messages('login.key11'/*汇联易用户使用协议*/)}
          visible={userProtocolVisible}
          footer={userFooter}
          onCancel={this.cancelProtocol}>
          <iframe src={href} width={600} height={400} style={{border: 'none'}}/>
        </Modal>
        {/*<div className="footer">{messages('login.key50')/*CopyRight 汇联易 | 沪ICP备16047366号*!/</div>*/}
      </div>
    )
  }
}

Login.contextTypes = {
  router: React.PropTypes.object
};
Login.propTypes = {
  onRef: React.PropTypes.func,//
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenant: state.login.tenant,
    tenantMode: state.main.tenantMode,//集团模式
    adminMode: state.main.adminMode,//管理员模式
    isOldCompany: state.login.isOldCompany,
    newPermissionSortedMenus: state.login.newPermissionSortedMenus,
    user: state.login.user,
  }
}

export default connect(mapStateToProps)(Login);

